<template>
  <el-table :data="renderData" border class="classify-table__item" size="mini">
    <!--  分类图标 -->
    <el-table-column align="center" label="分类图标" width="100">
      <template slot-scope="{row}">
        <el-image class="classify-icon__item" :src="row.icon | resourceUrl" />
        <input class="classify-icon-uploader__item" type="file" @change="onClickClassifyIconBtn(row)" title="点击上传" size="mini" />
      </template>
    </el-table-column>
    <!-- 分类名 -->
    <el-table-column label="分类名">
      <template slot-scope="{row}">
        <section class="classify-name-editor__group" v-if="row.edit">
          <el-input v-model="row.name" size="mini" />
          <el-button size="mini" @click="onClickSubmitBtn(row)" class="submit-btn__item" icon="el-icon-finished" type="success">提交</el-button>
        </section>
        <span v-else>{{ row.name }}</span>
      </template>
    </el-table-column>
    <!-- 创建时间 -->
    <el-table-column label="创建时间" width="180" align="center">
      <template slot-scope="{row}">
        <span class="el-icon-time">{{ new Date(row.created_at) | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
      </template>
    </el-table-column>
    <!-- 修改时间 -->
    <el-table-column label="修改时间" width="180" align="center">
      <template slot-scope="{row}">
        <span class="el-icon-time">{{ new Date(row.updated_at) | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
      </template>
    </el-table-column>
    <!-- 操作 -->
    <el-table-column align="right" width="185">
      <el-button size="mini" @click="onClickCreateClassifyBtn" icon="el-icon-plus" slot="header" type="info">新增</el-button>
      <template slot-scope="{$index,row}">
        <!-- 删除 -->
        <el-button size="mini" @click="onClickDeleteClassifyBtn( $index, row )" icon="el-icon-delete" type="danger" v-if="row.edit">删除</el-button>
        <!-- 编辑 -->
        <el-button size="mini" @click="onClickEditClassifyBtn( $index, row )" icon="el-icon-edit-outline" type="primary" v-if="!row.edit">编辑</el-button>
        <!-- 取消 -->
        <el-button size="mini" @click="onClickCancelClassifyBtn( $index, row )" icon="el-icon-refresh-left" type="warning" v-else>取消</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
import {
    createArchiveClassifyAPI,
    destroyArchvieClassifyAPI,
    updateArchiveClassifyNameAPI,
    findArchvieClassifyByTypeAPI,
    classifyIconUploaderAPI,
} from '@/api/archiveClassify';

export default {
    props: {
        archiveType: {
            type: Number,
            required: true,
        },
    },
    data() {
        return {
            renderData: [],
        };
    },
    created() {
        this.getClassifyData();
    },
    methods: {
    // 获取分类数据
        getClassifyData() {
            findArchvieClassifyByTypeAPI(this.archiveType).then(({ data }) => {
                // 重写分类数据
                this.renderData = data.map((element) => {
                    this.$set(element, 'edit', false);
                    this.$set(element, 'rawName', element.name);
                    return element;
                });
            }).catch(() => {
                this.$message.error('网络错误,请重试');
            });
        },
        // 点击新增按钮事件
        onClickCreateClassifyBtn() {
            this.$prompt('请输入分类名', '新建分类', {
                confirmButtonText: '确认新建',
                cancelButtonText: '取消新建',
            })
            // 点击弹框确认按钮
                .then(({ value }) => this.createClassifyHandler(value))
            // 点击弹框取消按钮
                .catch(() => this.$message({ type: 'info', message: '已取消新建' }));
        },
        // 添加分类处理器
        createClassifyHandler(name) {
            createArchiveClassifyAPI(this.archiveType, name).then(({ code }) => {
                // 添加成功
                if (code === 200) {
                    this.getClassifyData();
                } else if (code === 409) { // 分类已存在
                    this.$message.error('该分类已存在');
                }
            }).catch(() => {
                this.$message.error('网络错误,请重试');
            });
        },
        // 点击删除按钮事件
        onClickDeleteClassifyBtn(index, classify) {
            // 弹框确认
            this.$confirm('删除分类,该分类下的稿件会全部成为未分类状态,是否删除?', '删除分类提示', {
                confirmButtonText: '确认删除',
                cancelButtonText: '取消删除',
                type: 'warning',
            })
            // 点击弹框确认按钮
                .then(() => this.destoryClassHandler(classify.cid))
            // 点击弹框取消按钮
                .catch(() => this.$message({ type: 'info', message: '已取消删除' }));
        },
        // 删除分类处理器
        destoryClassHandler(cid) {
            destroyArchvieClassifyAPI(cid).then(({ code }) => {
                if (code === 200) {
                    this.getClassifyData();
                } else if (code === 400) {
                    this.$message.error('删除失败');
                }
            }).catch(() => {
                this.$message.error('网络错误,请重试');
            });
        },
        // 点击编辑按钮
        onClickEditClassifyBtn(index, classify) {
            classify.edit = true;
        },
        // 点击提交按钮
        async onClickSubmitBtn(row) {
            // 名称没有改变的话就直接退出函数
            if (row.name === row.rawName) {
                row.edit = false;
                return;
            }
            // 调用修改分类名称接口
            updateArchiveClassifyNameAPI(row.cid, row.name).then(({ code }) => {
                // 修改成功
                if (code === 200) {
                    row.edit = false;
                    row.rawName = row.name;
                    this.getClassifyData();
                } else if (code === 400) { //  分类id错误
                    this.$message.error('参数错误');
                }
            }).catch(() => {
                this.$message.error('网络错误,请重试');
            });
        },
        // 点击取消编辑按钮
        onClickCancelClassifyBtn(index, classify) {
            classify.edit = false;
            classify.name = classify.rawName;
        },
        // 点击图标按钮
        async onClickClassifyIconBtn(classifyObj) {
            // eslint-disable-next-line no-restricted-globals
            const img = event.target.files[0];
            const imgPath = window.URL.createObjectURL(img);
            // 开启遮罩
            const loading = this.$loading({
                lock: true,
                text: '图标上传中...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)',
            });
            // 显示图标
            classifyObj.icon = imgPath;
            // 进行上传操作
            await classifyIconUploaderAPI(classifyObj.cid, img);
            // 上传完成一秒后关闭遮罩
            setTimeout(() => {
                loading.close();
            }, 1000);
        },
    },
};
</script>

<style lang="scss" scoped>
// 表格
.classify-table__item {
  width: 100%;
  margin: auto;
  // 分类名称编辑器组
  .classify-name-editor__group {
    display: flex;
    align-items: center;
    // 提交按钮
    .submit-btn__item {
      margin-left: 10px;
    }
  }
  // 分类图标相关
  .classify-icon__item {
    width: 40px;
    height: 40px;
  }
  // 图标上传input道具
  .classify-icon-uploader__item {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    display: block;
    opacity: 0;
    cursor: pointer;
  }
}
</style>
